<template>
  <div class="report-upload">
    <!-- 编辑报告所属人弹窗 -->
    <EditReportUser
      ref="editUserDialogRef"
      :report-id="currentReportId"
      :current-name="currentUserName"
      @update="handleUpdateUser"
      @close="handleEditDialogClose"
    />
    <!-- 搜索区域 -->
    <el-form :model="searchForm" class="search-form" inline>
      <el-form-item style="width: 200px">
        <el-input
          v-model="searchForm.reportName"
          placeholder="搜索报告名"
          clearable
        />
      </el-form-item>

      <el-form-item style="width: 200px">
        <el-input
          v-model="searchForm.reportUserName"
          placeholder="搜索报告所属人"
          clearable
        />
      </el-form-item>

      <el-form-item style="width: 160px">
        <el-select
          v-model="searchForm.reportType"
          style="width: 160px"
          placeholder="报告类型"
          clearable
        >
          <el-option
            v-for="item in healthTypeList1"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item style="width: 240px">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="x"
          @change="handleDateChange"
        />
      </el-form-item>

      <el-form-item style="width: 200px">
        <el-input
          v-model="searchForm.uploadUserName"
          placeholder="搜索上传报告人"
          clearable
        />
      </el-form-item>

      <el-form-item style="width: 160px">
        <el-select
          v-model="searchForm.emergencyProcess"
          style="width: 160px"
          placeholder="紧急程度"
          clearable
        >
          <el-option :value="1" label="是" />
          <el-option :value="2" label="否" />
        </el-select>
      </el-form-item>

      <el-form-item style="width: 200px">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 状态Tab -->
    <el-tabs v-model="statusTab" class="status-tabs" @tab-click="handleSearch">
      <el-tab-pane
        v-for="item in staticTabsWithId"
        :key="item.id"
        :label="`${item.name} (${getStatusCount(item.name) || 0})`"
        :name="String(item.id)"
      />
    </el-tabs>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%"
      :empty-text="loading ? '加载中...' : '暂无数据'"
    >
      <!-- 报告名称列 -->
      <el-table-column prop="reportName" label="报告名称" min-width="250">
        <template #default="{ row }">
          <div class="report-name">
            <!-- v-if="row.emergencyFlag === 1" -->

            <span class="report-name-text" :title="row.reportName">
              {{ row.reportName }}</span
            >
            <span v-if="row.emergencyFlag === 1" class="emergency-tag">
              <el-tag type="danger" size="small">
                <el-icon><WarnTriangleFilled /></el-icon>紧急处理</el-tag
              >
            </span>
          </div>
        </template>
      </el-table-column>

      <!-- 报告所属人列 -->
      <el-table-column prop="reportUserName" label="报告所属人" min-width="120">
        <template #default="{ row }">
          <div class="user-name-wrapper">
            <el-tooltip
              v-if="row.reportUserName"
              :content="`ID: ${row.reportUserId}`"
              placement="top"
            >
              <span>{{ row.reportUserName }}</span>
            </el-tooltip>
            <span v-else class="no-data">--</span>

            <el-icon
              class="edit-icon"
              :class="{ 'no-user': !row.reportUserName }"
              @click="openEditDialog(row)"
            >
              <Edit />
            </el-icon>
          </div>
        </template>
      </el-table-column>

      <!-- 报告类型列 -->
      <el-table-column prop="reportType" label="报告类型" min-width="120">
        <template #default="{ row }">
          <span>{{ row.reportType || "--" }}</span>
        </template>
      </el-table-column>

      <!-- 上传者列 -->
      <el-table-column prop="uploadUserName" label="上传者" min-width="120">
        <template #default="{ row }">
          <el-tooltip
            v-if="row.uploadUserName"
            :content="`ID: ${row.uploadUserId}`"
            placement="top"
          >
            <span>{{ row.uploadUserName }}</span>
          </el-tooltip>
          <span v-else class="no-data">--</span>
        </template>
      </el-table-column>

      <!-- 上传时间列 -->
      <el-table-column
        prop="uploadTime"
        label="上传时间"
        sortable
        min-width="160"
      >
        <template #default="{ row }">
          <span>{{ row.uploadTime }}</span>
        </template>
      </el-table-column>

      <!-- 状态列 -->
      <el-table-column prop="statusName" label="状态" min-width="100">
        <template #default="{ row }">
          <div class="status-tag" :class="getStatusClass(row.status)">
            {{ row.statusName }}
          </div>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="{ row }">
          <div class="operation-buttons">
            <div class="button-group">
              <el-button
                v-show="row.showSupplementUser"
                type="primary"
                link
                @click="openEditDialog(row)"
              >
                补充报告所属人
              </el-button>
              <el-button
                v-show="row.showDownload"
                type="primary"
                link
                @click="handleDownload(row)"
              >
                下载
              </el-button>
              <el-button
                v-show="row.showDelete"
                type="primary"
                link
                @click="handleDelete(row)"
              >
                删除
              </el-button>
              <el-button
                v-show="row.showContentReview"
                type="primary"
                link
                @click="handleReview(row)"
              >
                前往审核校对
              </el-button>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="searchForm.pageNum"
        v-model:page-size="searchForm.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <VerifyReport ref="verifyReportRef" @close="handleSearch" />
  </div>
</template>

<script setup lang="ts">
import type {
  params,
  ReportUploadSearchSummaryVO,
  ReportUploadSearchVO
} from "@/api/addReport";
import { addReportApi } from "@/api/addReport";
import { reportApi } from "@/api/report-api";
import EditReportUser from "@/components/EditReportUser/index.vue";
import VerifyReport from "@/components/verifyReport/index.vue";
import { useToolsStore } from "@/store/modules/tools";
import { Edit, WarnTriangleFilled } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import { computed, nextTick, onMounted, reactive, ref } from "vue";

const toolsStore = useToolsStore();

const statusTab = ref();

// 编辑用户弹窗相关
const editUserDialogRef = ref();
const currentReportId = ref<number>();
const currentUserName = ref("");

// 打开编辑弹窗
const openEditDialog = (row: ReportUploadSearchVO) => {
  currentReportId.value = row.reportId;
  currentUserName.value = row.reportUserName || "";
  editUserDialogRef.value?.open(row.reportUserName);
};

// 关闭编辑弹窗
const handleEditDialogClose = () => {
  currentReportId.value = undefined;
  currentUserName.value = "";
};

// 更新用户信息
const handleUpdateUser = async (data: { reportId?: number; name: string }) => {
  try {
    // TODO: 调用更新用户信息的 API
    // const res = await addReportApi.updateReportUser({
    //   reportId: data.reportId,
    //   userName: data.name
    // });
    ElMessage.success("更新成功");
    // 重新加载数据
    handleSearch();
  } catch (error) {
    console.error("更新用户信息失败:", error);
    ElMessage.error("更新用户信息失败");
  }
};

const verifyReportRef = ref();

const handlePending = (reportId: number) => {
  verifyReportRef.value.open(reportId);
};

// 获取状态对应的统计数
const getStatusCount = (name: string): number => {
  switch (name) {
    case "全部":
      return totalSummary.value?.totalCount;
    case "待补充":
      return totalSummary.value?.pendingCompletionCount;
    case "待校对报告内容":
      return totalSummary.value?.pendingContentReview;
    case "AI分析中":
      return totalSummary.value?.aIAnalyzingCount;
    case "待校对报告指标":
      return totalSummary.value?.pendingIndicatorsReview;
    case "已审核":
      return totalSummary.value?.approvedCount;
    default:
      return 0;
  }
};
// 报告类型
const healthTypeList1 = computed(() => {
  return toolsStore.getDictData().healthTypeList || {};
});
// 报告状态类型
const healthStatusList = computed(() => {
  return toolsStore.getDictData().healthStatusList || [];
});
// 静态tab名称映射到动态ID
const staticTabsWithId = computed(() => {
  // 定义静态的tab名称
  const staticTabNames = [
    "全部",
    "待补充",
    "待校对报告内容",
    "待校对报告指标",
    "AI分析中",
    "已审核"
  ];

  return staticTabNames.map(name => {
    // 从healthStatusList中找到对应的ID
    const foundItem = healthStatusList.value.find(item => item.name === name);
    return {
      id: foundItem ? foundItem.id : "", // 如果找不到就用名称作为ID
      name: name
    };
  });
});

// // 监听状态tab变化
// watch(statusTab, (newVal, oldVal) => {
//   // 只有在用户手动切换状态时才调用接口
//   if (oldVal !== "") {
//     handleSearch();
//   }
// });

// 搜索表单
const searchForm = reactive<params>({
  pageNum: 1,
  pageSize: 10,
  reportName: "",
  reportUserName: "",
  reportType: undefined,
  uploadUserName: "",
  emergencyProcess: undefined,
  startDate: "",
  endDate: ""
});

// 日期范围
const dateRange = ref();

// 表格数据
const tableData = ref<ReportUploadSearchVO[]>([]);
const loading = ref(false);
const total = ref(0);

// 统计数据
const totalSummary = ref<ReportUploadSearchSummaryVO>({});

// 处理日期变化
const handleDateChange = (val: [string, string] | null) => {
  if (val) {
    searchForm.startDate = val[0];
    searchForm.endDate = val[1];
  } else {
    searchForm.startDate = "";
    searchForm.endDate = "";
  }
};

// 格式化时间
const formatDate = (date: string | undefined): string => {
  if (!date) return "--";
  return dayjs(date).format("YYYY-MM-DD");
};

// 获取状态样式类名
const getStatusClass = (status: number): string => {
  const statusMap: Record<number, string> = {
    2: "status-pending", // 待补充
    3: "status-approved", // 已审核
    4: "status-review", // 待审核
    6: "status-rejected", // 已驳回
    5: "status-expired" // 已过期
  };
  return statusMap[status] || "status-default";
};

// 获取统计数据
const getReportSummary = async () => {
  try {
    const params: params = {
      pageNum: searchForm.pageNum,
      pageSize: searchForm.pageSize,
      reportName: searchForm.reportName,
      reportUserName: searchForm.reportUserName,
      reportType: searchForm.reportType,
      uploadUserName: searchForm.uploadUserName,
      emergencyProcess: searchForm.emergencyProcess,
      startDate: searchForm.startDate,
      endDate: searchForm.endDate
    };
    const res = await addReportApi.reportEntrySearchSummaryApi(params);
    if (res.code === 0) {
      const data = res.data;
      totalSummary.value = data;
    }
  } catch (error) {
    console.error("获取报告统计数据失败:", error);
  }
};

// 搜索
const handleSearch = async () => {
  loading.value = true;
  try {
    await nextTick(); // 等待 DOM 更新
    // 设置状态ID
    searchForm.reportStatusId = statusTab.value;

    const res = await addReportApi.getReportList(searchForm);
    tableData.value = res.data.list || [];
    total.value = res.data.total || 0;
  } catch (error) {
    console.error("获取报告列表失败:", error);
    ElMessage.error("获取报告列表失败");
  } finally {
    loading.value = false;
  }
};

// 重置
const handleReset = () => {
  searchForm.reportName = "";
  searchForm.reportUserName = "";
  searchForm.reportType = undefined;
  searchForm.uploadUserName = "";
  searchForm.emergencyProcess = undefined;
  searchForm.startDate = "";
  searchForm.endDate = "";
  dateRange.value = null;
  handleSearch();
};

// 分页相关
const handleSizeChange = (val: number) => {
  searchForm.pageSize = val;
  handleSearch();
};

const handleCurrentChange = (val: number) => {
  searchForm.pageNum = val;
  handleSearch();
};

// 操作相关
const handleSupplementInfo = (row: ReportUploadSearchVO) => {
  // 补充报告所属人逻辑
  console.log("补充报告所属人:", row);
};

const handleDownload = async (row: ReportUploadSearchVO) => {
  try {
    const res = await addReportApi.download({
      reportId: row.reportId as number
    });

    const downloadUrls = res?.data?.downloadUrls;
    if (downloadUrls?.length) {
      // 创建一个隐藏的 a 标签来下载文件
      const downloadLink = document.createElement("a");
      downloadLink.style.display = "none";
      document.body.appendChild(downloadLink);

      // 下载所有文件
      downloadUrls.forEach(url => {
        downloadLink.href = url;
        downloadLink.download = url.split("/").pop() || "report.pdf"; // 从 URL 获取文件名
        downloadLink.click();
      });

      document.body.removeChild(downloadLink);
      ElMessage.success("开始下载");
    } else {
      ElMessage.warning("未找到可下载的文件");
    }
  } catch (error) {
    console.error("下载失败:", error);
    ElMessage.error("下载失败");
  }
};

const handleDelete = (row: ReportUploadSearchVO) => {
  if (!row.reportId) {
    ElMessage.warning("报告ID不能为空");
    return;
  }

  ElMessageBox.confirm("确定要删除该报告吗？删除后不可恢复", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const res = await addReportApi.delete({
        reportId: row.reportId
      });

      ElMessage.success("删除成功");
      // 重新加载数据
      handleSearch();
    })
    .catch(() => {
      // 用户取消删除，不做任何操作
    });
};

// onMounted(() => {
//   handlePending(4006);
// });

const handleReview = (row: ReportUploadSearchVO) => {
  // 前往审核校对逻辑
  console.log("前往审核校对:", row);
  handlePending(row.reportId || 4006);
};

// 获取字典数据
const getDictData = async () => {
  try {
    const res = await reportApi.queryReportDict();
    if (res?.data) {
      toolsStore.setDictData(res.data);
    }
  } catch (error) {
    console.error("获取字典数据失败:", error);
    ElMessage.error("获取字典数据失败");
  }
};

// 组件激活时的处理
const handleActivated = async () => {
  await getDictData();
  // 获取统计数据
  await getReportSummary();
  // 设置默认选中第一个状态
  if (staticTabsWithId.value?.length > 0) {
    statusTab.value = staticTabsWithId.value[0].id;
    // 直接调用一次搜索，而不是通过 watch 触发
    handleSearch();
  }
};

// 导出方法供父组件调用
// 组件挂载时初始化
onMounted(() => {
  handleActivated();
});

defineExpose({
  handleActivated
});
</script>

<style lang="scss" scoped>
.report-upload {
  .user-name-wrapper {
    display: flex;
    align-items: center;
    gap: 8px;

    .edit-icon {
      cursor: pointer;
      color: #909399;
      font-size: 16px;
      transition: all 0.3s;

      &:hover {
        color: #409eff;
      }

      &.no-user {
        color: #c0c4cc;
      }
    }
  }

  .search-form {
    background: #fff;
    padding: 20px 0;
    border-radius: 4px;
    margin-bottom: 20px;
  }

  .status-tabs {
    margin-bottom: 20px;
    :deep(.el-tabs__nav) {
      background: #fff;
      padding: 0 20px;
      border-radius: 4px;
    }
  }

  .report-name {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    flex-direction: column;

    .emergency-tag {
      flex-shrink: 0;
    }

    .report-name-text {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .operation-buttons {
    .button-group {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;

      :deep(.el-button) {
        padding: 0;
        height: 22px;
        line-height: 22px;
        font-size: 14px;
        margin: 0;
      }
    }
  }

  .no-data {
    color: #999;
  }

  .pagination-container {
    margin-top: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 4px;
    display: flex;
    justify-content: flex-end;
  }

  .status-tag {
    display: inline-flex;
    align-items: center;
    height: 24px;
    padding: 0 8px;
    font-size: 12px;
    line-height: 24px;
    border-radius: 4px;
    box-sizing: border-box;
    white-space: nowrap;
    border: 1px solid transparent;

    &.status-pending {
      color: #222222;
      border-color: #ffb634;
      background-color: #fff1c4;
    }

    &.status-review {
      color: #222222;
      border-color: #b3d8ff;
      background-color: #ecf5ff;
    }

    &.status-approved {
      color: #222222;
      border-color: #c2e7b0;
      background-color: #f0f9eb;
    }

    &.status-rejected {
      color: #222222;
      border-color: #44d7b6;
      background-color: #c9fff3;
    }

    &.status-expired {
      color: #222222;
      border-color: #d3d4d6;
      background-color: #f4f4f5;
    }

    &.status-default {
      color: #909399;
      border-color: #d3d4d6;
      background-color: #f4f4f5;
    }
  }
}
</style>
